package dao

import (
	"context"
	"device-admin/internal/dal"
	"device-admin/internal/define"
	"device-admin/internal/models"
	"time"
)

// 操作日志
type OperationLog struct{}

// Add 增加操作日志
func (OperationLog) Add(
	ctx context.Context,
	query *dal.Query,
	records []*models.OperationLog,
	batchSize int,
	objExistsFunc ExistsFunc,
	associationObjExistsFunc ExistsFunc,
) error {
	// 对象存在性验证
	validRecords := []*models.OperationLog{}
	for _, record := range records {
		var exists1, exists2 bool
		if objExistsFunc != nil && record.ObjID != "" {
			exists1 = objExistsFunc(ctx, query, record.ObjID)
		} else {
			exists1 = true
		}
		if associationObjExistsFunc != nil && record.AssociationID != "" {
			exists2 = associationObjExistsFunc(ctx, query, record.AssociationID)
		} else {
			exists2 = true
		}
		if exists1 && exists2 {
			validRecords = append(validRecords, record)
		}
	}
	ol := query.OperationLog
	ol.WithContext(ctx).CreateInBatches(validRecords, batchSize)
	return nil
}

// List 获取操作日志
func (OperationLog) List(
	ctx context.Context,
	query *dal.Query,
	operationType define.OperationType, // 操作类型
	objID string, // 操作对象
	associationID string, // 关联对象id
	startTime, endTime int64, // 开始和结束时间
	page, limit int, // 分页参数
) (list []*models.OperationLog, total int64, err error) {
	ol := query.OperationLog
	// 操作类型
	tx := ol.WithContext(ctx).Where(ol.OperationType.Eq(int(operationType)))
	// 开始和结束时间
	if endTime <= 0 {
		endTime = time.Now().Unix()
	}
	if startTime > 0 && endTime > 0 {
		tx = tx.Where(ol.CreatedAt.Between(startTime, endTime))
	}
	// 对象id
	if objID != "" {
		tx = tx.Where(ol.ObjID.Eq(objID))
	}
	// 关联对象id
	if associationID != "" {
		tx = tx.Where(ol.AssociationID.Eq(associationID))
	}
	// 获取总条数
	total, _ = tx.Count()
	if total == 0 {
		return []*models.OperationLog{}, 0, nil
	}
	// 获取分页记录
	list, _ = tx.
		Offset(GetPageOffset(page, limit)).
		Limit(GetPageLimit(limit)).
		Order(ol.ID.Desc()).
		Find()
	return list, total, nil
}
